#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
模拟完整文件处理流程的调试脚本
用于复现 "无法获取佣金率" 的问题
"""

import requests
import configparser
import json
import sys

def parse_filename(filename):
    """解析文件名获取商品ID和标题 - 复制自main.py的逻辑"""
    print(f"正在解析文件名: {filename}")
    
    # 情况1: 标准格式 "商品id{ID} 视频标题{标题}.mp4"
    if filename.startswith("商品id") and " 视频标题" in filename:
        try:
            # 提取商品ID
            id_part = filename.split(" 视频标题")[0]
            product_id = id_part.replace("商品id", "")
            
            # 提取标题（去掉.mp4扩展名）
            title_part = filename.split(" 视频标题")[1]
            title = title_part.replace(".mp4", "")
            
            print(f"✅ 标准格式解析成功 - 商品ID: {product_id}, 标题: {title}")
            return product_id, title
        except Exception as e:
            print(f"❌ 解析标准格式文件名出错: {filename}, 错误: {str(e)}")
    
    # 情况2: 紧凑格式 "商品id{ID}视频标题{标题}.mp4" (没有空格)
    elif filename.startswith("商品id") and "视频标题" in filename:
        try:
            # 提取商品ID
            id_part = filename.split("视频标题")[0]
            product_id = id_part.replace("商品id", "")
            
            # 提取标题（去掉.mp4扩展名）
            title_part = filename.split("视频标题")[1]
            title = title_part.replace(".mp4", "")
            
            print(f"✅ 紧凑格式解析成功 - 商品ID: {product_id}, 标题: {title}")
            return product_id, title
        except Exception as e:
            print(f"❌ 解析紧凑格式文件名出错: {filename}, 错误: {str(e)}")
    
    # 情况3: 商品ID后有空格的情况 "商品 id{ID} 视频标题{标题}.mp4"
    elif filename.startswith("商品 id") and " 视频标题" in filename:
        try:
            # 提取商品ID
            id_part = filename.split(" 视频标题")[0]
            product_id = id_part.replace("商品 id", "")
            
            # 提取标题（去掉.mp4扩展名）
            title_part = filename.split(" 视频标题")[1]
            title = title_part.replace(".mp4", "")
            
            print(f"✅ 带空格格式解析成功 - 商品ID: {product_id}, 标题: {title}")
            return product_id, title
        except Exception as e:
            print(f"❌ 解析带空格格式文件名出错: {filename}, 错误: {str(e)}")
    
    # 情况4: 商品ID后有空格且没有视频标题空格的情况 "商品 id{ID}视频标题{标题}.mp4"
    elif filename.startswith("商品 id") and "视频标题" in filename:
        try:
            # 提取商品ID
            id_part = filename.split("视频标题")[0]
            product_id = id_part.replace("商品 id", "")
            
            # 提取标题（去掉.mp4扩展名）
            title_part = filename.split("视频标题")[1]
            title = title_part.replace(".mp4", "")
            
            print(f"✅ 带空格紧凑格式解析成功 - 商品ID: {product_id}, 标题: {title}")
            return product_id, title
        except Exception as e:
            print(f"❌ 解析带空格紧凑格式文件名出错: {filename}, 错误: {str(e)}")
            
    print(f"❌ 无法解析文件名格式: {filename}")
    return None, None

def get_commission_rate(product_id, config):
    """获取佣金率 - 复制自main.py的逻辑但添加更多调试信息"""
    max_retries = 3
    retry_delay = 10  # 初始重试延迟10秒
    
    print(f"\n=== 获取佣金率: {product_id} ===")
    
    for attempt in range(max_retries):
        try:
            api_url = config.get('kuaishou', 'api_url')
            cookie = config.get('kuaishou', 'cookie')
            
            print(f"尝试 {attempt + 1}/{max_retries}")
            print(f"API URL: {api_url}")
            
            headers = {
                'Referer': 'https://cps.kwaixiaodian.com/pc/promoter/selection-center/home',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 QuarkPC/4.5.5.535',
                'Trace-id': '1.0.0.1759207323819.12',
                'Origin': 'https://cps.kwaixiaodian.com',
                'Kpf': 'PC_WEB',
                'Ktrace-str': '3|My40NTgzNjk4Mjg2NzM2NzY5Ljg4NzU5Nzc5LjE3NTkyMDczMjM4MjAuMTAyNQ==|My40NTgzNjk4Mjg2NzM2NzY5Ljc1NDgzOTQ2LjE3NTkyMDczMjM4MjAuMTAyNA==|0|plateco-kfx-service|plateco|true|src:Js,seqn:7456,rsi:52a1f2d9-83d9-4bc3-b15d-020622163cdb,path:/pc/promoter/selection-center/home,rpi:9db83bca4a',
                'Sec-ch-ua': '?0',
                'Sec-ch-ua-platform': '"macOS"',
                'Sec-fetch-dest': 'empty',
                'Sec-fetch-mode': 'cors',
                'Sec-fetch-site': 'same-origin',
                'Cookie': cookie,
                'Content-Type': 'application/json',
                'Accept': '*/*',
                'Host': 'cps.kwaixiaodian.com',
                'Connection': 'keep-alive'
            }
            
            data = {
                "orderType": 0,
                "channelId": 99,
                "keyWord": product_id,
                "pcursor": "1_1",
                "requestType": 0
            }
            
            print(f"发送请求数据: {json.dumps(data)}")
            
            response = requests.post(api_url, headers=headers, json=data, timeout=30)
            
            print(f"响应状态码: {response.status_code}")
            
            # 检查HTTP状态码
            if response.status_code != 200:
                print(f"❌ 快手API HTTP错误: {response.status_code}, 商品ID: {product_id}")
                if response.status_code == 429:  # 限流错误
                    print(f"检测到限流，重试...")
                    continue
                return None
                
            result = response.json()
            print(f"API响应结果概览: result={result.get('result')}, data字段存在={bool(result.get('data'))}")
            
            if result.get('data'):
                print(f"data数组长度: {len(result['data'])}")
                if len(result['data']) > 0:
                    first_item = result['data'][0]
                    print(f"第一个商品的commissionRate字段: {first_item.get('commissionRate')}")
            
            # 检查API返回的结果状态
            if result.get("result") != 1:
                error_msg = result.get("errorMsg", "未知错误")
                print(f"❌ 快手API返回错误: {error_msg}, 商品ID: {product_id}")
                
                # 检查是否是限流错误
                if "限流" in error_msg or "too many requests" in error_msg.lower() or "rate limit" in error_msg.lower():
                    print(f"检测到限流，重试...")
                    continue
                
                return None
            
            # 检查数据是否存在
            if not result.get("data"):
                print(f"❌ 快手API返回空数据, 商品ID: {product_id}")
                return None
                
            # 提取佣金率
            commission_rate = result["data"][0].get("commissionRate")
            if commission_rate is None:
                print(f"❌ 快手API返回数据中未找到佣金率, 商品ID: {product_id}")
                return None
                
            print(f"✅ 成功获取佣金率: {commission_rate}")
            return str(commission_rate)
            
        except Exception as e:
            print(f"❌ 请求异常: {str(e)}")
            if attempt < max_retries - 1:
                print(f"等待重试...")
                continue
            return None
    
    print(f"❌ 快手API请求失败，已达到最大重试次数 ({max_retries})，商品ID: {product_id}")
    return None

def simulate_file_processing(filename):
    """模拟完整的文件处理流程"""
    print(f"{'='*60}")
    print(f"模拟处理文件: {filename}")
    print(f"{'='*60}")
    
    # 加载配置
    config = configparser.ConfigParser()
    config.read('config.ini', encoding='utf-8')
    
    # 步骤1: 解析文件名
    result = parse_filename(filename)
    if result is None or len(result) != 2:
        print(f"❌ 无法解析文件名: {filename}")
        return False
        
    product_id, title = result
    if not product_id or not title:
        print(f"❌ 无法解析文件名: {filename}")
        return False
    
    # 步骤2: 获取佣金率
    commission_rate = get_commission_rate(product_id, config)
    if not commission_rate:
        print(f"❌ 无法获取佣金率: {filename}")
        return False
    
    print(f"✅ 文件处理成功!")
    print(f"   商品ID: {product_id}")
    print(f"   标题: {title}")
    print(f"   佣金率: {commission_rate}%")
    
    return True

if __name__ == "__main__":
    # 测试文件名
    test_filename = "商品id21535007340517 视频标题安琪小白条酵母，宝妈必备！发面快速，馒头包子面包吐司松软香甜，宝宝爱吃妈妈省心！1.mp4"
    
    if len(sys.argv) > 1:
        test_filename = sys.argv[1]
    
    success = simulate_file_processing(test_filename)
    
    if success:
        print(f"\n🎉 模拟处理成功")
    else:
        print(f"\n❌ 模拟处理失败")